<?php

	class DatabaseHandler {
		
		private $mysqli = NULL;
		
		//Funktion som ansluter till databasen.
		public function Connect(databaseSettings $settings)
		{
			$this->mysqli = new mysqli($settings->host, 
								$settings->user, 
								$settings->password, 
								$settings->database);
			
			if ($this->mysqli->connect_error)
			{
				throw new Exeption($this->mysqli->coconnect_error);
			}
			$this->mysqli->set_charset("utf8");
			return true;
		}
		
		//Funktion som stänger anslutningen till databasen.
		public function Close()
		{
			return $this->mysqli->close();
		}
		
		public function PrepareSql($sqlQuery)
		{
			$stmt = $this->mysqli->prepare($sqlQuery);
			if($stmt == false)
			{
				throw new Exception(mysqli_error());
			}
			return $stmt;
		}
		
		//Execute query som returnerar.
		public function ExecuteAndReturnQuery(mysqli_stmt $stmt)
		{
			if($stmt->execute() == false)
			{
				throw new Exception(mysqli_error());
			}			return $stmt;
		}
		
		//Execute query utan return.
		public function ExecuteQuery(mysqli_stmt $stmt)
		{
			if($stmt->execute() == false)
			{
				throw new Exception(mysqli_error());
			}
			$stmt->Close();
		}
		
		//test funktion
		public static function Test(DatabaseSettings $settings)
		{
			$database = new DatabaseHandler();
			
			if ($database->Connect($settings) == false)
			{
				echo "Det gick inte att ansluta till databasen.";
				return false;
			}
			if ($database->Close() == false)
			{
				echo "Det gick inte att avsluta anslutningen till databasen.";
				return false;
			}
			return true;
		}
	}
?>